package com.mach.platform.sprider.dev.virdev;

import com.mach.platform.sprider.dev.ByteUtil;
import com.mach.platform.sprider.getter.GeneralModbusDev;
import com.mach.platform.sprider.getter.MainWork;
import com.mach.platform.sprider.getter.DataLogService;
import com.mach.platform.util.SqlHelper;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;

@Slf4j
public class SimpleValveDev extends GeneralModbusDev implements VirDev {

    public static final long OPEN_FAK_TIMEOUT_VALUE = 60 * 1000;

    private SqlHelper sqlHelper;
    private  DataLogService dataLogService;
    private  Map<String, Object> devInfoMap;
    private  Integer devId;
    private Integer cmdCode = 3;


    public SimpleValveDev(Map<String, Object> devInfoMap, SqlHelper sqlHelper, DataLogService dataLogService) throws SQLException {
        super(devInfoMap, sqlHelper, dataLogService);

        this.devInfoMap = devInfoMap;

        this.sqlHelper = sqlHelper;

        this.dataLogService = dataLogService;

    }

    public String getOpenCmdStr(){
        String result = "" + devId +  ":open";

        return result;
    }

    public String getCloseCmdStr(){
        String result = "" + devId +  ":close";

        return result;
    }


    @Override
    protected void pick() {
//        "select dev.id devId, dev.name name,type.prol prol,  dev.dev_type_id devTypeId,\n" +
//                " coll.id collId, coll.name collName, coll.value_addr collAddr,\n " +
//                " dev.comm_addr commAddr,\n" +
//                " coll.data_len collLen, coll.data_type collDataType,\n"；

        Map<Integer, Object> collMap = (Map<Integer, Object>) this.devInfoMap.get("coll");

        Set<Map.Entry<Integer, Object>> collEntrys = collMap.entrySet();

        for(Map.Entry<Integer, Object> collEntry : collEntrys){
            Map<String, Object> coll = (Map<String, Object>) collEntry.getValue();

            Integer devId = (Integer)this.devInfoMap.get("devId");
            String collName = (String)coll.get("collName");
            BigDecimal collAddr = (BigDecimal)coll.get("collAddr");
            Integer collLen = (Integer)coll.get("collLen");
            this.cmdCode = (Integer)coll.get("collFunCode");
            if(cmdCode == null) cmdCode = 3;
            String collDataType = (String)coll.get("collDataType");
            String collUnit = (String)coll.get("collUnit");
            String prol = (String)this.devInfoMap.get("prol");
            Object result = null;

//            log.info("collName"+ collName);

            try {
                byte[] databuf = null;
                if("SimpleValveDevGeneralModbusRTU".equals(prol)){
                    byte[] orgData = this.dh.getDataRtu(collAddr.intValue(), 2, cmdCode);
                   if(orgData == null || orgData.length <1)continue;
                    databuf = ByteUtil.subData(orgData,3,collLen.intValue());


                }else
                if ("SimpleValveDevGeneralModbusTCP".equals(prol)){
                    byte[] orgData = this.dh.getDataTcp(collAddr.intValue(), 2, cmdCode);
                   if(orgData == null || orgData.length <1)continue;
                    databuf = ByteUtil.subData(orgData,9,collLen.intValue());
                }

                databuf = ByteUtil.reverse(databuf);
                Short resultInt = ByteUtil.getShort(databuf);
                result = resultInt;

                if( "开到位".equals(collName) ){

                    if(resultInt == 1){
//                        result = "到位";
                        result = 1;
                    }else if(resultInt == 0){
//                        result = "未到位";
                        result = 0;
                    }else{
//                        result = "未知";
                    }


                }

                if( "关到位".equals(collName) ){
                    if(resultInt == 1){
//                        result = "到位";
                        result = 1;
                    }else if(resultInt == 0){
//                        result = "未到位";
                        result = 0;
                    }else{
//                        result = "未知";
                    }

                }

                if( "开状态".equals(collName) ){
                    if(resultInt == 1){
//                        result = "打开中";
                        result = 1;
                    }else if(resultInt == 0){
//                        result = "停止";
                        result = 0;
                    }else{
                        result = "未知";
                    }

                }

                if( "关状态".equals(collName) ){

                    if(resultInt == 1){
//                        result = "关闭中";
                        result = 1;
                    }else if(resultInt == 0){
//                        result = "停止";
                        result = 0;
                    }else{
//                        result = "未知";
                    }

                }





            }catch (Exception e){
                e.printStackTrace();
                System.err.println("error msg:" + e.getLocalizedMessage() + " devId=" + this.devId + "");
                result = null;
            }

            if(result != null){
                try {
                    MainWork.addResult(devInfoMap, coll, result);
                    //this.dataLogService.addDataLogAsync(devId, new Date(), collName, result);

                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("error saveToDb... msg:" + e.getLocalizedMessage() + " devId=" + this.devId + "");
                }
            }

        }

    }

    @Override
    public void cmd(Integer cmdLogId,String cmd, String param) {

        try {

            BigDecimal openAddr = (BigDecimal)addrMap.get("开输出");
            BigDecimal openStatusAddr = (BigDecimal)addrMap.get("开到位");
            if("startOpen".equals(cmd) && (null != openAddr)){
                this.dh.setDataRtu(openAddr.intValue(), 1); //设置状态
                long startTime = System.currentTimeMillis();
                try {
                    while(true){
                        Short stat = this.dh.getShortData(openStatusAddr.intValue(), cmdCode);
                        if(stat != null && stat == 1){
                            sqlHelper.update(
                                    "update iot_dev_cmd_log set resp_code=1,resp_ctx='"+EXE_SUCS_CTX+"' where id=" + cmdLogId);
                            break;
                        }
                        long cur = System.currentTimeMillis();
                        long dt = cur - startTime;
                        if(dt > OPEN_FAK_TIMEOUT_VALUE){
                            sqlHelper.update(
                                    "update iot_dev_cmd_log set resp_code=2,resp_ctx='TimeOut' where id=" + cmdLogId);
                            break;
                        }
                        Thread.sleep(20);
                    }
                } finally {
                    this.dh.setDataRtu(openAddr.intValue(), 0); //设置状态
                }
            }


            if("stopOpen".equals(cmd)){
                //this.dh.setDataRtu(addr, 0);
            }



            BigDecimal closeAddr = (BigDecimal)addrMap.get("关输出");
            BigDecimal closeStatusAddr = (BigDecimal)addrMap.get("关到位");
            if("startClose".equals(cmd) && (null != closeAddr)){
                this.dh.setDataRtu(closeAddr.intValue(), 1); //设置状态
                long startTime = System.currentTimeMillis();
                try {
                    while(true){
                        Short stat = this.dh.getShortData(closeStatusAddr.intValue(), cmdCode);
                        if(stat == 1){
                            sqlHelper.update(
                                    "update iot_dev_cmd_log set resp_code=1,resp_ctx='"+EXE_SUCS_CTX+"' where id=" + cmdLogId);
                            break;
                        }
                        long cur = System.currentTimeMillis();
                        long dt = cur - startTime;
                        if(dt > OPEN_FAK_TIMEOUT_VALUE){
                            sqlHelper.update(
                                    "update iot_dev_cmd_log set resp_code=2,resp_ctx='"+EXE_SUCS_CTX+"' where id=" + cmdLogId);
                            break;
                        }
                    }
                } finally {
                    this.dh.setDataRtu(closeAddr.intValue(), 0); //设置状态
                }
            }
            if("stopClose".equals(cmd) && (null != closeAddr)){
                //this.dh.setDataRtu(addr, 0);
            }




        } catch (Exception e) {
            e.printStackTrace();
            sqlHelper.updateAsync(
                    "update iot_dev_cmd_log set resp_code=0,resp_ctx='"+e.getLocalizedMessage()+"' where id=" + cmdLogId);
        }finally {
            sqlHelper.updateAsync(
                    "update iot_dev_cmd_log set resp_time=now() where id=" + cmdLogId);
        }




        return;
    }




}
